package com.happyscan138.makefun;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.happyscan138.makefun.Urls.Urls;
import com.happyscan138.makefun.base.WaitNetDataPop;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.auth.AccessTokenKeeper;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbConnectErrorMessage;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;

import cz.msebera.android.httpclient.Header;

import static com.happyscan138.makefun.Urls.Urls.QQ;
import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2016/12/2.
 */

public class Land extends AppCompatActivity implements View.OnClickListener {
    private TextView rerurnPassword,clickregister,lanright,landleft;
    private EditText landUser,landPassword;
    private Button landButton;
    private CheckBox landChecxBox;
    private AsyncHttpClient client;
    private RequestParams params;
    //声明一个SharedPreferences对象和一个Editor对象
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    //注册成功之后的APPKEY (微信)
    private static final String App_ID="wxb3ba5a6e1c615e27";
    public static IWXAPI api;
    private ImageButton WeixinLand,BlogLand,QQLand;
    private WaitNetDataPop pop;
    /** 显示认证后的信息，如 AccessToken */
    private TextView mTokenText;
    /** 封装了 "access_token"，"expires_in"，"refresh_token"，并提供了他们的管理功能  */
    private Oauth2AccessToken mAccessToken;
    /** 注意：SsoHandler 仅当 SDK 支持 SSO 时有效 */
    private SsoHandler mSsoHandler;
    private static final String APPID = "1106200714";//官方获取的APPID
    private Tencent mTencent;
    private BaseUiListener mIUiListener;
    private UserInfo mUserInfo;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.land);
        pop=new WaitNetDataPop(this);
        registerToWx();
        initView();
        //获取preferences和editor对象
        preferences =this.getSharedPreferences("UserInfo", MODE_PRIVATE);
        String name = preferences.getString("userName","");
        String password = preferences.getString("passWord", "");
        boolean isChecked= preferences.getBoolean("checkboxBoolean",false);
        log.e("fdfff",isChecked+"");
        if(isChecked){
            landUser.setText(name);
            log.e("fdfff",name);
            landPassword.setText(password);
            landChecxBox.setChecked(true);
        }
        WbSdk.install(this,new AuthInfo(this, ConstantsBlog.APP_KEY, ConstantsBlog.REDIRECT_URL, ConstantsBlog.SCOPE));
        mTencent = Tencent.createInstance(APPID,Land.this.getApplicationContext());

    }

    private void registerToWx() {
        api = WXAPIFactory.createWXAPI(this, App_ID, false);
        api.registerApp(App_ID);
    }
    public void initView(){
        //找回密码和点击注册添加下划线
        rerurnPassword=(TextView)findViewById(R.id.returen_password);
        rerurnPassword.setOnClickListener(this);
        rerurnPassword.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        clickregister=(TextView)findViewById(R.id.register);
        clickregister.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        clickregister.setOnClickListener(this);
        landUser=(EditText)findViewById(R.id.land_user);
        landPassword=(EditText) findViewById(R.id.land_password);
        landButton=(Button)findViewById(R.id.land_button);
        landButton.setOnClickListener(this);
        landChecxBox=(CheckBox)findViewById(R.id.land_checkBox);
        WeixinLand=(ImageButton)findViewById(R.id.Weixin);
        WeixinLand.setOnClickListener(this);
        BlogLand=(ImageButton) findViewById(R.id.blog);
        BlogLand.setOnClickListener(this);
        QQLand=(ImageButton)findViewById(R.id.QQlogin);
        QQLand.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.QQlogin:
                mIUiListener = new BaseUiListener();
                //all表示获取所有权限
                mTencent.login(Land.this,"all", mIUiListener);
                break;
            case R.id.Weixin:
                if (!api.isWXAppInstalled()) {
                    Toast.makeText(Land.this, "未安装微信客户端，请先下载",
                            Toast.LENGTH_LONG).show();
                    return;
                }
                    final SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "wechat_sdk_demo_test";
                   api.sendReq(req);
 
                break;
            case R.id.returen_password:{
                startActivity(new Intent(this,returnPassword.class));
                break;
            }
            case R.id.register:
                startActivity(new Intent(this,register.class));
                break;
            case R.id.land_button:
                String name = landUser.getText().toString();
                String pswd = landPassword.getText().toString();
                if(name.trim().equals("")){
                    Toast.makeText(this, "请您输入用户名！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(pswd.trim().equals("")){
                    Toast.makeText(this, "请您输入密码！", Toast.LENGTH_SHORT).show();
                    return;
                }
                boolean CheckBoxLogin = landChecxBox.isChecked();

               if (CheckBoxLogin){
                   editor= preferences.edit();
                   editor.putString("userName",name);
                   editor.putString("passWord",pswd);
                   editor.putBoolean("checkboxBoolean",true);
                   editor.commit();
               }else {
                   editor= preferences.edit();
                   editor.putString("userName", null);
                   editor.putString("passWord", null);
                   editor.putBoolean("checkboxBoolean", false);
                   editor.commit();
               }
                client=new AsyncHttpClient();
                params=new RequestParams();
                params.put("user_name",name);
                params.put("pwd",pswd);
                client.post(Urls.land, params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        String jsonStr=response.toString();
                        try {
                            JSONObject jsonObject = new JSONObject(jsonStr);
                            String code=jsonObject.getString("code");
                            String msg = jsonObject.getString("msg");
                            int code_int=Integer.valueOf(code).intValue();
                            if(code_int==202) {
                                Toast.makeText(Land.this, msg, Toast.LENGTH_LONG).show();
                            }
                            if(code_int==1){
                                Toast.makeText(Land.this, msg, Toast.LENGTH_LONG).show();
                                JSONObject jsonObject1=jsonObject.getJSONObject("data");
                                String access_key=jsonObject1.getString("access_key");
                                editor.putString("UserId",access_key);
                                //获取收藏标签
                                RequestParams paramsLike=new RequestParams();
                                paramsLike.put("access_key",access_key);
                                client.post(Urls.LikeList,paramsLike,new JsonHttpResponseHandler(){
                                    @Override
                                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                        super.onSuccess(statusCode, headers, response);
                                        String json=response.toString();
                                        try {
                                            JSONObject jsonObject2=new JSONObject(json);
                                            JSONArray jsonArray=jsonObject2.getJSONArray("data");
                                            for (int i=0;i<jsonArray.length();i++){
                                                JSONObject objectData=jsonArray.getJSONObject(0);
                                                String like_type_id=objectData.getString("like_type_id");
                                                editor.putString("LikeTypeID",like_type_id);
                                                String UserID=objectData.getString("user_id");
                                                editor.putString("persionalID",UserID);
                                                log.e("LikeTypeID",like_type_id);
                                                editor.commit();
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                                startActivity(new Intent(Land.this,MainActivity.class));

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                        super.onFailure(statusCode, headers, responseString, throwable);
                    }
                });

                break;
            case R.id.blog:
                mSsoHandler = new SsoHandler(Land.this);
                mSsoHandler.authorize(new SelfWbAuthListener());
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        preferences =this.getSharedPreferences("UserInfo", MODE_PRIVATE);
        String name = preferences.getString("userName","");
        String password = preferences.getString("passWord", "");
        boolean isChecked= preferences.getBoolean("checkboxBoolean",false);
        log.e("fdfff",isChecked+"");
        if(isChecked){
            landUser.setText(name);
            log.e("fdfff",name);
            landPassword.setText(password);
            log.e("fdfff",password);
            landChecxBox.setChecked(true);
        }else {
            landUser.setText(null);
            log.e("fdfff",name);
            landPassword.setText(null);
            log.e("fdfff",password);
            landChecxBox.setChecked(true);
        }
        pop.dismiss();
    }


    /**
     * 当 SSO 授权 Activity 退出时，该函数被调用。
     *
     * @see
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // SSO 授权回调
        // 重要：发起 SSO 登陆的 Activity 必须重写 onActivityResults
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
        if(requestCode == Constants.REQUEST_LOGIN){
            Tencent.onActivityResultData(requestCode,resultCode,data,mIUiListener);
        }

    }


    private class SelfWbAuthListener implements com.sina.weibo.sdk.auth.WbAuthListener{
        @Override
        public void onSuccess(final Oauth2AccessToken token) {
            Land.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mAccessToken = token;
                    if (mAccessToken.isSessionValid()) {
                            params=new RequestParams();
                            client=new AsyncHttpClient();
                            params.put("uid",mAccessToken.getUid());
                            client.post(Urls.Blog,params,new JsonHttpResponseHandler(){
                                @Override
                                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                    super.onSuccess(statusCode, headers, response);
                                    Log.e("ooodooddo",response.toString());
                                    try {
                                        JSONObject jsonObject=new JSONObject(response.toString());
                                        int code=jsonObject.getInt("code");
                                        if(code==1){
                                            JSONObject data=jsonObject.getJSONObject("data");
                                            String key=data.getString("access_key");
                                            log.e("ooodooddo",key);
                                            editor= preferences.edit();
                                            editor.putString("UserId",key);
                                            editor.commit();
                                            Toast.makeText(Land.this,jsonObject.getString("msg"),Toast.LENGTH_SHORT).show();
                                            startActivity(new Intent(Land.this,MainActivity.class));

                                        }else if(code==2) {
                                            Toast.makeText(Land.this,jsonObject.getString("msg"),Toast.LENGTH_SHORT).show();

                                                    AsyncHttpClient client= new AsyncHttpClient(true, 80, 443);
                                                    RequestParams params=new RequestParams();
                                                    params.put("appkey", ConstantsBlog.APP_KEY);
                                                    params.put("access_token",mAccessToken.getToken());
                                                    params.put("uid",mAccessToken.getUid());
                                                    Log.e("ooodooddo",params.toString());
                                                    client.post("https://api.weibo.com/2/users/show.json?",params,new JsonHttpResponseHandler(){
                                                        @Override
                                                        public void onStart() {
                                                            super.onStart();
                                                            Log.e("ooodooddo","onStart");
                                                        }

                                                        @Override
                                                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                                            super.onSuccess(statusCode, headers, response);
                                                            Log.e("ooodooddo",response.toString());
                                                            Log.e("ooodooddo",statusCode+"");
                                                            try {
                                                                JSONObject jsonObject1=new JSONObject(response.toString());
                                                                String name=jsonObject1.getString("name");
                                                                Intent intent=new Intent();
                                                                intent.putExtra("nick",name);
                                                                intent.putExtra("uid",mAccessToken.getUid());
                                                                intent.setClass(Land.this,register.class);
                                                                startActivity(intent);
                                                            } catch (JSONException e) {
                                                                e.printStackTrace();
                                                            }
                                                        }
                                                        @Override
                                                        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                                                            super.onFailure(statusCode, headers, responseString, throwable);
                                                            Log.e("ooodooddo",responseString);
                                                        }

                                                        @Override
                                                        public void onFinish() {
                                                            super.onFinish();
                                                            Log.e("ooodooddo","onFinish");
                                                        }
                                                    });
                                                }
                                            Log.e("ooodooddo","fgfgfgfg");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });


                        // 显示 Token
                        updateTokenView(false);
                        // 保存 Token 到 SharedPreferences
                        AccessTokenKeeper.writeAccessToken(Land.this, mAccessToken);
//                        Toast.makeText(Land.this, R.string.weibosdk_demo_toast_auth_success, Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

        @Override
        public void cancel() {
            Toast.makeText(Land.this,
                    R.string.weibosdk_demo_toast_auth_canceled, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(WbConnectErrorMessage errorMessage) {
            Toast.makeText(Land.this, errorMessage.getErrorMessage(), Toast.LENGTH_LONG).show();
        }

    }

    /**
     * 显示当前 Token 信息。
     *
     * @param hasExisted 配置文件中是否已存在 token 信息并且合法
     */
    private void updateTokenView(boolean hasExisted) {
        String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(
                new java.util.Date(mAccessToken.getExpiresTime()));
        String format = getString(R.string.weibosdk_demo_token_to_string_format_1);
//        mTokenText.setText(String.format(format, mAccessToken.getToken(), date));
        String message = String.format(format, mAccessToken.getToken(), date);
        if (hasExisted) {
            message = getString(R.string.weibosdk_demo_token_has_existed) + "\n" + message;
        }
//        mTokenText.setText(message);
    }
    /**
     * 自定义监听器实现IUiListener接口后，需要实现的3个方法
     * onComplete完成 onError错误 onCancel取消
     */
    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            log.e("response", response.toString());
            Toast.makeText(Land.this, "授权成功", Toast.LENGTH_SHORT).show();
            JSONObject obj = (JSONObject) response;
            try {
                final String openID = obj.getString("openid");
                String accessToken = obj.getString("access_token");
                String expires = obj.getString("expires_in");
                mTencent.setOpenId(openID);
                mTencent.setAccessToken(accessToken, expires);
                QQToken qqToken = mTencent.getQQToken();
                mUserInfo = new UserInfo(getApplicationContext(), qqToken);
                mUserInfo.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object response) {
                        log.e("response", response.toString());
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            final String name = jsonObject.getString("nickname");
                            params = new RequestParams();
                            client = new AsyncHttpClient();
                            params.put("open_id", openID);
                            params.put("nick_name", name);
                            client.post(QQ, params, new JsonHttpResponseHandler() {
                                @Override
                                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                    super.onSuccess(statusCode, headers, response);
                                    log.e("response", response.toString());
                                    try {
                                        JSONObject jsonObject1 = new JSONObject(response.toString());
                                        JSONObject jsonObject2 = jsonObject1.getJSONObject("data");
                                        String acc_key = jsonObject2.getString("access_key");
                                        editor = preferences.edit();
                                        editor.putString("UserId", acc_key);
                                        editor.commit();
                                        startActivity(new Intent(Land.this, MainActivity.class));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(UiError uiError) {
                    }

                    @Override
                    public void onCancel() {

                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(Land.this, "授权失败", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onCancel() {
            Toast.makeText(Land.this, "授权取消", Toast.LENGTH_SHORT).show();
        }


    }


}
